// pages/Taskdetail/lindex.js
import ajax from "../network/index"
import {
  uploadFile,
  prePicTure,
  uploadPicture
} from "../../utils/upload"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    result: [],
    code: "",
    materialVoList: '',
    resultStatus: '',
    detailedList: '',
    paymentList: "",
    userId: "",
    auditing: false,
    auditPage: false,
    auditingVoList: "",
    projectName: "",
    modal: false,
    showInputComment: false,
    showPop: false,
    btnLoading: false,
    discountAmountBtn: "",
    memo: "",
    mydiscountAmount: '',
    mydiscountMemo: "",
    subjectCode: "",
    orderNos: []
  },
  move() {},
  masking() {
    this.setData({
      auditPage: false,
    })
  },
  openPop() {
    this.setData({
      showPop: true
    });
  },
  onClose() {
    this.setData({
      showPop: false,
    });
  },
  previewImg(e) {
    let index = e.currentTarget.dataset.index
    let list = this.data.materialVoList
    if (!list[index].img) {
      wx.showToast({
        icon: "none",
        title: "暂无图片",
        duration: 1500
      })
      return
    }
    let urls = list.map(item => item.img)
    wx.previewImage({
      current: list[index].img,
      urls,
    })
  },
  //调起回复
  showInputComment() {

    this.setData({
      showInputComment: !this.data.showInputComment
    })
  },
  //回复内容
  comment(e) {
    let content = e.detail
    let _this = this
    ajax({
      url: "/submit",
      method: "POST",
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      data: {
        reimbursedCode: this.data.code,
        userId: this.data.userId,
        content
      }
    }).then(v => {
      if (v.code != 200) {
        wx.showToast({
          title: v.msg
        })
        return
      }
      wx.showToast({
        title: '发送成功！',
        success: function (v) {
          _this.setData({
            showInputComment: false
          })
          _this.getDetail()
        }
      })
    })
  },
  couponPriceChange(e) {
    this.setData({
      mydiscountAmount: e.detail
    })
  },
  memoChange(e) {
    this.setData({
      mydiscountMemo: e.detail
    })
  },

  //提交优惠
  confirmCoupon() {
    let _this = this
    if (!this.data.mydiscountAmount) {
      wx.showToast({
        title: '请输入正确的金额！',
        icon: "none"
      })
      return
    }
    this.setData({
      btnLoading: true
    })
    ajax({
      url: "/api/reimbursed/reimbursedEditDiscountAmount",
      method: "POST",
      data: {
        reimbursedCode: this.data.code,
        discountAmount: this.data.mydiscountAmount,
        memo: this.data.mydiscountMemo
      }
    }).then(res => {
      _this.setData({
        btnLoading: false
      })
      if (res.code == 200) {
        _this.setData({
          showPop: false
        })
        _this.getDetail()
        wx.showToast({
          title: res.msg,
          duration: 1500
        })
      } else {
        wx.showToast({
          icon: "none",
          title: res.msg
        })
      }
    }).catch(() => {
      this.setData({
        btnLoading: false
      })
    })
  },
  //打开预览
  replenishListPre(e) {

    prePicTure(e, this.data.result.replenishList)
  },
  uploadPictrue() {
    let _this = this
    let imgData = []
    uploadPicture().then(v => {
      v.forEach(file => {
        imgData.push({
          source: file.fileType,
          url: file.url,
          type: 3
        })
      })
      ajax({
        url: "/api/reimbursed/replenishSubmit",
        method: "POST",
        data: {
          imgData,
          userId: this.data.userId,
          reimbursedCode: this.data.code
        }
      }, 'application/json').then(v => {
        console.log(v)
        if (v.code != 200) {
          wx.showToast({
            title: v.msg,
          })
          return
        }
        wx.showToast({
          title: '补充票据完成',
        })
        _this.setData({
          modal: false
        })
        this.getDetail()
      })
    })

  },
  //上传图片
  uploadFile() {
    let _this = this
    let imgData = []
    uploadFile().then(v => {

      v.forEach(file => {
        imgData.push({
          source: file.fileType,
          url: file.url,
          type: 3
        })
      })
      ajax({
        url: "/api/reimbursed/replenishSubmit",
        method: "POST",
        data: {
          imgData,
          userId: this.data.userId,
          reimbursedCode: this.data.code
        }
      }).then(v => {
        console.log(v)
        if (v.code != 200) {
          wx.showToast({
            title: v.msg,
          })
          return
        }
        wx.showToast({
          title: '补充票据完成',
        })
        _this.setData({
          modal: false
        })
        this.getDetail()
      })


    })


  },

  //关闭弹窗
  cancel() {
    this.setData({
      modal: false
    })
  },
  //补充
  replenish() {
    this.setData({
      modal: !this.data.modal
    })
  },
  //修改报销内容
  UpdatecContent() {
    console.log(this.data.result, 'this.data.result');

    wx.setStorageSync('detail', this.data.result)
    wx.navigateTo({
      url: "/pages/updateDetail/lindex",
    })
  },
  //查看重复分析
  repetitionDetail(e) {
    let id = e.currentTarget.dataset.id
    if (!(id == this.data.code)) {
      wx.navigateTo({
        url: "/pages/Taskdetail/lindex?code=" + id
      })
    } else {
      wx.showToast({
        title: "当前编号为当前详情",

      })
    }

  },
  //删除任务
  delExpense() {
    if (!this.data.isdelete) {
      return
    }
    let _this = this
    wx.showModal({
      title: "提示",
      content: "是否删除该报销流程",
      success(res) {
        if (res.confirm) {
          ajax({
            url: "/api/reimbursed/userDeleteReimbursedRecord",
            method: "POST",
            header: {
              'Content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              userId: _this.data.userId,
              reimbursedCode: _this.data.code,
            }
          }).then(v => {
            if (v.code == 200) {
              wx.showToast({
                title: '删除成功',
                success: function () {
                  wx.navigateBack({
                    delta: 1,
                  })
                }
              })

            } else {
              wx.showToast({
                icon: "none",
                title: v.msg,
              })
            }
          })
        } else if (res.cancel) {
          wx.showToast({
            icon: "none",
            title: '取消删除',
          })
        }
      }
    })
  },
  //修改任务
  updExpense() {

  },
  closePopup() {
    this.masking()
  },
  audit() {
    this.setData({
      auditPage: true
    })
  },
  submitInvoice(e) {
    let {
      image,
      memo,
      status,
      subjectCode,
      type //1、同意 2、拒绝
    } = e.detail
    if ( this.data.subjectCode) {
      if (type == 1 && !subjectCode) {
        wx.showToast({
          title: '请选择科目！',
          icon: "none"
        })
        return
      }
    }
    wx.showLoading({
      title: '提交中...',
    })
    // 提交审核
    ajax({
      url: "/api/reimbursed/auditing",
      method: "POST",
      data: {
        auditingResult: status,
        imgs: image,
        memo,
        subjectCode,
        userId: this.data.userId,
        reimbursedCode: this.data.code
      }
    }).then(v => {
      wx.hideLoading()
      if (v.code == 200) {
        this.setData({
          auditPage: false,
          auditing: false
        })
        wx.showToast({
          title: '审批成功',
        })
      } else {
        wx.showToast({
          title: v.msg,
        })
      }
    }).catch(() => {
      wx.hideLoading()
    })
  },
  //大图预览
  paymentListPre(e) {
    let file = e.currentTarget.dataset.file.source
    let currentImage = e.currentTarget.dataset.currentimage
    if (file != 'image') {
      wx.showLoading({
        title: '正在打开文件..',
      })
      wx.downloadFile({
        url: currentImage,
        success: (v) => {
          const filePath = v.tempFilePath
          wx.openDocument({
            showMenu: true,
            filePath: filePath,
            success: function (v) {
              wx.hideLoading({
                success: (res) => {},
              })
              console.log(v)
            },
            fail: function () {
              wx.hideLoading({
                success: (res) => {},
              })
              wx.showModal({
                title: '提示',
                content: "在线打开文件失败，是否下载到本地",
                success: (res) => {
                  if (res.confirm) {
                    wx.saveFile({

                      tempFilePath: filePath,
                      success: (v) => {
                        wx.showToast({
                          icon: 'none',
                          title: '下载成功保存在' + v.savedFilePath,
                        })
                      },
                      fail: () => {
                        wx.showToast({
                          title: '下载失败，请联系管理员',
                          icon: "none"
                        })
                      }
                    })
                  } else if (res.cancel) {
                    wx.showToast({
                      title: '取消下载',
                      icon: "none"
                    })
                  }
                }
              })
            }
          })
        }
      })
    } else {
      let urlsData = this.data.paymentList
      let urls = urlsData.map(v => {
        return v.url
      })
      wx.previewImage({
        current: currentImage,
        urls,
      })
    }

  },
  getDetail() {
    ajax({
      url: "/api/reimbursed/userReimbursedRecordDetail",
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        code: this.data.code,
        userId: this.data.userId
      }
    }).then(v => {
      if (v.code == 200) {
        let result = v.data
        v.data.materialVoList.forEach(item => {
          item.materialNum = parseInt(item.materialNum)
          item.total = item.materialAmout.substr(0, item.materialAmout.length - 1)
        })
        let materialVoList = v.data.materialVoList
        let auditingVoList = v.data.auditingVoList
        let detailedList = v.data.detailedList
        let resultStatus = v.data.resultStatus
        let paymentList = v.data.paymentList
        let auditing = v.data.auditing
        let projectName = v.data.projectName
        let isdelete = v.data.isdelete
        let discountAmountBtn = v.data.discountAmountBtn
        let discountAmount = v.data.discountAmount
        let discountMemo = v.data.discountMemo
        let subjectCode = v.data.subjectCode
        let orderNos = v.data.orderNos
        this.setData({
          detailedList,
          result,
          resultStatus,
          materialVoList,
          paymentList,
          auditing,
          auditingVoList,
          projectName,
          isdelete,
          discountAmountBtn,
          discountAmount,
          discountMemo,
          subjectCode,
          orderNos
        })
      } else {
        wx.showToast({
          title: v.msg,
        })
      }

    })
  },
  detailedListPre(e) {
    let file = e.currentTarget.dataset.file.source
    let currentImage = e.currentTarget.dataset.currentimage
    if (file != 'image') {
      wx.showLoading({
        title: '正在打开文件..',
      })
      wx.downloadFile({
        url: currentImage,
        success: (v) => {
          const filePath = v.tempFilePath
          wx.openDocument({
            showMenu: true,
            filePath: filePath,
            success: function () {
              wx.hideLoading({
                success: (res) => {},
              })
            },
            fail: function () {
              wx.hideLoading({
                success: (res) => {},
              })
              wx.showModal({
                title: '提示',
                content: "在线打开文件失败，是否下载到本地",
                success: (res) => {

                  if (res.confirm) {

                    wx.saveFile({
                      tempFilePath: filePath,
                      success: (v) => {
                        wx.showToast({
                          icon: 'none',
                          title: '下载成功保存在' + v.savedFilePath,
                        })
                      },
                      fail: () => {
                        wx.showToast({
                          title: '下载失败，请联系管理员',
                          icon: "none"
                        })
                      }
                    })
                  } else if (res.cancel) {
                    wx.showToast({
                      title: '取消下载',
                      icon: "none"
                    })
                  }
                }
              })
            }
          })
        }
      })
    } else {
      let urlsData = this.data.detailedList
      let urls = urlsData.map(v => {
        return v.url
      })
      wx.previewImage({
        current: currentImage,
        urls,
      })
    }


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let code = options.code
    this.setData({
      code
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let userId = wx.getStorageSync('userId')
    this.setData({
      userId
    })
    if (userId) {
      this.getDetail()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})